const CryptoJS = require("crypto-js");
const AES = require("crypto-js/aes");
const utf8 = require("crypto-js/enc-utf8");
const md5 = require("crypto-js/md5");

const iv = utf8.parse("qwertyuiop123456");
const ivLogin = utf8.parse("8765432112345678");
const mode = CryptoJS.mode.CBC;
const padding = require("crypto-js/pad-pkcs7");

const default_key = "junbokey12345678";
const contentSession = "62f26dec856b3f01c17b864afa8c56b1";

const user_key = "SqoP1Q=A";

import crypto from 'crypto-js';

export default {
   encrypt (data, key) {
      let real_key = utf8.parse(md5(key || default_key).toString().slice(0, 16));
      let bytes = AES.encrypt(data, real_key, {
         iv: iv,
         mode: mode,
         padding: padding
      });
      return bytes.toString();
   },
   encryptLogin (data, key) {
      if (typeof data !== "string") {
         data = window.JSON.stringify(data);
      }
      let real_key = utf8.parse(md5(contentSession + key).toString().slice(0, 16));
      let bytes = AES.encrypt(data, real_key, {
         iv: ivLogin,
         mode: mode,
         padding: padding
      });
      return bytes.ciphertext.toString(); //hex
   },
   decrypt (data, key) {
      if (!data) return null;
      let real_key = utf8.parse(md5(key || default_key).toString().slice(0, 16));
      let bytes = AES.decrypt(data, real_key, {
         iv: iv,
         mode: mode,
         padding: padding
      });
      return bytes.toString(utf8);
   },

   encryptDes (message, key = 'SqoP1Q=A') {
      var keyHex = crypto.enc.Utf8.parse(key)
      var option = { mode: crypto.mode.ECB, padding: crypto.pad.Pkcs7 }
      var encrypted = crypto.DES.encrypt(message, keyHex, option)
      return encrypted.toString(); // 返回hex格式密文，如需返回base64格式：encrypted.toString()
   },

   decryptDes (message, key = 'SqoP1Q=A') {
      var keyHex = crypto.enc.Utf8.parse(key)
      var decrypted = crypto.DES.decrypt(
         {
            ciphertext: crypto.enc.Base64.parse(message)
         }, // 若 message 是 base64 格式，则无需转16进制hex，直接传入 message 即可
         keyHex,
         {
            mode: crypto.mode.ECB,
            padding: crypto.pad.Pkcs7
         }
      )
      return decrypted.toString(crypto.enc.Utf8)
   }
}